﻿using System.Text.RegularExpressions;

namespace DTweet.Helpers
{
    public static class LinksHandlerExtensions
    {
        private static readonly Regex Regex = new Regex("((http://|www\\.)([A-Z0-9.-:]{1,})\\.[0-9A-Z?;~&#=\\-_\\./]{2,})", RegexOptions.Compiled | RegexOptions.IgnoreCase);
        private const string Link = "<a href=\"{0}{1}\" target=\"_blank\" rel=\"nofollow\">{2}</a>";

        public static string ResolveLinks(this string body)
        {
            if (string.IsNullOrEmpty(body))
                return body;

            foreach (Match match in Regex.Matches(body))
            {
                body = body.Replace(match.Value, !match.Value.Contains("://") ? string.Format(Link, "http://", match.Value, ShortenUrl(match.Value, 50)) : string.Format(Link, string.Empty, match.Value, ShortenUrl(match.Value, 50)));
            }

            return body;
        }

        private static string ShortenUrl(string url, int max)
        {
            if (url.Length <= max)
                return url;

            // Remove the protocal
            int startIndex = url.IndexOf("://");
            if (startIndex > -1)
                url = url.Substring(startIndex + 3);

            if (url.Length <= max)
                return url;

            // Remove the folder structure
            var firstIndex = url.IndexOf("/") + 1;
            var lastIndex = url.LastIndexOf("/");
            if (firstIndex < lastIndex)
                url = url.Replace(url.Substring(firstIndex, lastIndex - firstIndex), "...");

            if (url.Length <= max)
                return url;

            // Remove URL parameters
            var queryIndex = url.IndexOf("?");
            if (queryIndex > -1)
                url = url.Substring(0, queryIndex);

            if (url.Length <= max)
                return url;

            // Remove URL fragment
            var fragmentIndex = url.IndexOf("#");
            if (fragmentIndex > -1)
                url = url.Substring(0, fragmentIndex);

            if (url.Length <= max)
                return url;

            // Shorten page
            firstIndex = url.LastIndexOf("/") + 1;
            lastIndex = url.LastIndexOf(".");
            if (lastIndex - firstIndex > 10)
            {
                var page = url.Substring(firstIndex, lastIndex - firstIndex);
                var length = url.Length - max + 3;
                url = url.Replace(page, "..." + page.Substring(length));
            }

            return url;
        }
    }
}